package com.arunsawad.ilertu.activity;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Base64;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.arunsawad.ilertu.R;
import com.arunsawad.ilertu.common.AsyncActivity;
import com.arunsawad.ilertu.common.Constants;
import com.arunsawad.ilertu.common.ILertU;
import com.arunsawad.ilertu.common.RequestTask;
import com.arunsawad.ilertu.common.Utils;
import com.arunsawad.ilertu.common.Validator;

public class Lert extends Activity implements AsyncActivity, LocationListener {
	SharedPreferences preferences;
	AlertDialog.Builder alertDialogBuilder;
	private static final int TAKE_PICTURE = 0;
	private static final int SELECT_PICTURE = 1;
	ImageView imgPicture;
	AlertDialog alert;
	String imgBase64;
	double latitude;
	double longitude;
	double accuracy;
	ProgressDialog bar;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.act_lert);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
				R.layout.title2_imgbtn_txt_btn);

		initTitle();

		preferences = getSharedPreferences(Constants.PREF_FILE, MODE_PRIVATE);

		Validator.Validate(this, preferences);

		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			((ILertU) this.getApplication()).setLertServiceId(extras
					.getString("serviceId"));
		}

		init();
	}

	public void initTitle() {
		ImageButton imgBtn1 = (ImageButton) findViewById(R.id.title2_imgBtn1);
		imgBtn1.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(getApplicationContext(), Home.class);
				startActivity(intent);
			}
		});

		TextView txtTitle = (TextView) findViewById(R.id.title2_txtTitle);
		txtTitle.setText(getString(R.string.lert));

		Button btn = (Button) findViewById(R.id.title2_btn);
		btn.setText(getString(R.string.lert));
		btn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				lert();
			}
		});
	}

	public void init() {
		// get gps location
		LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		lm.requestLocationUpdates("gps", 0, 0, this);
		Location location = lm
				.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		if (location != null) {
			latitude = location.getLatitude();
			longitude = location.getLongitude();
			accuracy = location.getAccuracy();
			TextView txtLatitude = (TextView) findViewById(R.id.lert_latitude);
			txtLatitude.setText("Latitude: " + String.valueOf(latitude));
			TextView txtLongitude = (TextView) findViewById(R.id.lert_longitude);
			txtLongitude.setText("Longitude: " + String.valueOf(longitude));
			TextView txtAccuracy = (TextView) findViewById(R.id.lert_accuracy);
			txtAccuracy.setText("Accuracy: " + String.valueOf(accuracy));
		}

		// handle taken picture
		imgPicture = (ImageView) findViewById(R.id.lert_image);
		// set image if taken
		String path = ((ILertU) this.getApplication()).getImagePath();
		if (!path.equals("")) {
			File imgFile = new File(path);
			if (imgFile.exists()) {
				Bitmap myBitmap = BitmapFactory.decodeFile(imgFile
						.getAbsolutePath());
				ByteArrayOutputStream bytes = new ByteArrayOutputStream();
				myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);

				byte[] b = bytes.toByteArray();
				imgBase64 = Base64.encodeToString(b, Base64.DEFAULT);

				imgPicture.setImageBitmap(myBitmap);
			}
		}

		// set values
		((EditText) findViewById(R.id.lert_txtMessage)).setText(((ILertU) this
				.getApplication()).getLertMessage());
	}

	public void beforeLeave() {
		((ILertU) this.getApplication())
				.setLertMessage(((EditText) findViewById(R.id.lert_txtMessage))
						.getText().toString());
	}

	// {{ onClick events
	public void changeImage(View view) {
		alertDialogBuilder = new Builder(Lert.this);
		alertDialogBuilder.setTitle(getString(R.string.photo_options));
		String[] types = { getString(R.string.take_photo),
				getString(R.string.image_from_gallery) };
		alertDialogBuilder.setItems(types,
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						switch (which) {
						case 0:
							Intent intent = new Intent(
									"android.media.action.IMAGE_CAPTURE");
							startActivityForResult(intent, TAKE_PICTURE);
							break;
						case 1:
							Intent photoPickerIntent = new Intent();
							photoPickerIntent.setType("image/*");
							photoPickerIntent
									.setAction(Intent.ACTION_GET_CONTENT);
							startActivityForResult(photoPickerIntent,
									SELECT_PICTURE);
							break;
						default:
							break;
						}
					}
				});
		alertDialogBuilder.show();
	}

	public void lertToFriends(View view) {

	}

	public void lertToGroups(View view) {

	}

	public void lert() {
		bar = new ProgressDialog(Lert.this);
		bar.setIndeterminate(true);
		bar.show();

		String filter = "";
		filter += "	<lert>";
		filter += "		<note>"
				+ ((EditText) findViewById(R.id.lert_txtMessage)).getText()
				+ "</note>";
		filter += "		<image>";
		filter += "			<imageSource>" + imgBase64 + "</imageSource>";
		filter += "			<postType>1</postType>";
		filter += "		</image>";
		filter += "		<location>";
		filter += "			<latitude>" + latitude + "</latitude>";
		filter += "			<longitude>" + longitude + "</longitude>";
		filter += "			<satelliteNumber/>";
		filter += "			<accuracy>" + accuracy + "</accuracy>";
		filter += "			<accuracyMeters/>";
		filter += "			<accuracyYards/>";
		filter += "		</location>";
		filter += "		<share>";
		filter += "			<service id=\""
				+ ((ILertU) this.getApplication()).getLertServiceId() + "\"/>";
		filter += "			<social shareToFacebook=\""
				+ ((ILertU) this.getApplication()).getLertShareToFb()
				+ "\" shareToTwitter=\""
				+ ((ILertU) this.getApplication()).getLertShareToTt() + "\" />";
		filter += "			<friends all=\""
				+ ((ILertU) this.getApplication()).getLertShareToAllFriends()
				+ "\">";
		if (!((ILertU) this.getApplication()).getLertShareToAllFriends()) {
			JSONArray friends = ((ILertU) this.getApplication())
					.getLertFriends();
			for (int i = 0; i < friends.length(); i++) {
				JSONObject friend;
				try {
					friend = friends.getJSONObject(i);
					filter += "        <friend id=\"" + friend.get("id")
							+ "\" />";
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		}
		filter += "            </friends>";
		filter += "			<groups all=\""
				+ ((ILertU) this.getApplication()).getLertShareToAllGroups()
				+ "\">";
		if (!((ILertU) this.getApplication()).getLertShareToAllGroups()) {
			JSONArray groups = ((ILertU) this.getApplication()).getLertGroups();
			for (int i = 0; i < groups.length(); i++) {
				JSONObject group;
				try {
					group = groups.getJSONObject(i);
					filter += "        <group id=\"" + group.get("id")
							+ "\" />";
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		}
		filter += "            </groups>";
		filter += "		</share>";
		filter += "	</lert>";

		String msg = String.format(Constants.MSG, "ilertu.lerts-add",
				preferences.getString(Constants.PREF_USER_NAME, ""),
				preferences.getString(Constants.PREF_PASSWORD, ""),
				preferences.getString(Constants.PREF_LANGUAGE, "en"), filter);

		RequestTask task = new RequestTask();
		task.setListener(this);
		task.execute(Constants.URL_LERT, msg);
	}

	// }}

	// {{ callback
	// taking/selecting picture
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		String imagePath = "";
		Bitmap photo = null;
		if (requestCode == TAKE_PICTURE) {
			if (data != null) {
				photo = (Bitmap) data.getExtras().get("data");
			}
		} else {
			if (requestCode == SELECT_PICTURE) {
				Uri uri = data.getData();
				String path = Utils.getPathFromURI(this, uri);
				int orientation = Utils.getImageAngle(this, uri);
				photo = Utils.getImageFromPath(this, path, orientation);
			}
		}
		photo = Utils.resizeImage(photo, Constants.LERT_IMAGE_WIDTH,
				Constants.LERT_IMAGE_HEIGHT);
		try {
			imagePath = Environment.getExternalStorageDirectory()
					+ File.separator + Constants.TEMP_IMAGE;
			ByteArrayOutputStream bytes = new ByteArrayOutputStream();
			photo.compress(Bitmap.CompressFormat.JPEG, 100, bytes);

			byte[] b = bytes.toByteArray();
			imgBase64 = Base64.encodeToString(b, Base64.DEFAULT);

			File f = new File(imagePath);
			if (f.exists()) {
				f.delete();
			}

			// write the bytes in file
			FileOutputStream fo = new FileOutputStream(imagePath);
			fo.write(bytes.toByteArray());

			fo.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		imgPicture.setImageBitmap(photo);

		((ILertU) this.getApplication()).setImagePath(imagePath);
	}

	@Override
	public void onRequestCompleted(String results) {
		if (results != null) {
			DocumentBuilderFactory factory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder builder;
			try {
				builder = factory.newDocumentBuilder();
				Document document = builder.parse(new InputSource(
						new StringReader(results)));
				NodeList nodes = document.getElementsByTagName("error");
				String message = "";
				if (nodes.getLength() > 0) {
					Element e = (Element) nodes.item(0);

					message = e.getElementsByTagName("errorDesc").item(0)
							.getTextContent();
				} else {
					message = getString(R.string.lert_successful);
				}
				alertDialogBuilder = new AlertDialog.Builder(this);
				alertDialogBuilder
						.setMessage(message)
						.setCancelable(false)
						.setPositiveButton(R.string.ok,
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int id) {
										dialog.cancel();
									}
								});
				alert = alertDialogBuilder.create();
				alert.show();

				// hide progress bar
				bar.hide();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	// }}

	@Override
	public void onLocationChanged(Location location) {
		latitude = location.getLatitude();
		longitude = location.getLongitude();
		accuracy = location.getAccuracy();
		TextView txtLatitude = (TextView) findViewById(R.id.lert_latitude);
		txtLatitude.setText("Latitude: " + String.valueOf(latitude));
		TextView txtLongitude = (TextView) findViewById(R.id.lert_longitude);
		txtLongitude.setText("Longitude: " + String.valueOf(longitude));
		TextView txtAccuracy = (TextView) findViewById(R.id.lert_accuracy);
		txtAccuracy.setText("Accuracy: " + String.valueOf(accuracy));
	}

	@Override
	public void onProviderDisabled(String provider) {
	}

	@Override
	public void onProviderEnabled(String provider) {
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
	}
}